package mi.payment.ui.base;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import mi.payment.R;

/**
 * @author sunmi on 2017/1/10.
 */
public class PromptDialog extends Dialog {

    private static int countSeconds;
    private static PromptDialog promptDialog;
    private static TextView ok;
    private static Context context;
    private static View.OnClickListener onClickListener1;

//    public PromptDialog(Context context) {
//        super(context);
//        this.context = context;
//    }

    public PromptDialog(Context context, int theme) {
        super(context, theme);
        this.context = context;
    }

    public static PromptDialog createDialog(Context context, final View.OnClickListener onClickListener, final View.OnClickListener cancelOnClickListenter) {
        TextView cancel;
        promptDialog = new PromptDialog(context, sunmi.sunmiui.R.style.defaultDialogStyle);
        promptDialog.setContentView(R.layout.dialog_prompt);
        promptDialog.getWindow().getAttributes().gravity = Gravity.CENTER; //居中
        promptDialog.setCanceledOnTouchOutside(true); //点击空白不取消
        promptDialog.setCancelable(true); //点击返回按钮不取消
        ok = (TextView) promptDialog.findViewById(R.id.ok);
        cancel = (TextView) promptDialog.findViewById(R.id.cancel);
        countSeconds = 10;
        mHandler.sendEmptyMessage(0);
        onClickListener1 = onClickListener;
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.removeCallbacksAndMessages(null);
                onClickListener.onClick(v);
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.removeCallbacksAndMessages(null);
                promptDialog.dismiss();
                cancelOnClickListenter.onClick(v);
            }
        });
        return promptDialog;
    }


    static Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (countSeconds > 0) {
                --countSeconds;
                ok.setText(Html.fromHtml(context.getResources().getString(R.string.dialog_time, "<font color='#999999'>（" + countSeconds + "）</font>")));
                mHandler.sendEmptyMessageDelayed(0, 1000);
            } else {
                onClickListener1.onClick(ok);
                countSeconds = 10;
                mHandler.removeMessages(0);
            }
        }
    };

    public void hideDialog() {
        if (promptDialog != null) {
            mHandler.removeCallbacksAndMessages(null);
            promptDialog.dismiss();
        }
    }

}
